package com.ioftv.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ioftv.common.Result;
import com.ioftv.dto.BusinessStatisticsExcelDTO;
import com.ioftv.dto.ImportResultDTO;
import com.ioftv.dto.PageQuery;
import com.ioftv.dto.PageResult;
import com.ioftv.entity.BusinessStatistics;
import com.ioftv.listener.BusinessStatisticsImportListener;
import com.ioftv.service.BusinessStatisticsService;
import com.ioftv.util.UserContextUtil;
import com.ioftv.util.RolePermissionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 业务统计控制器
 * 处理业务统计数据的增删改查操作
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class BusinessStatisticsController {

    @Autowired
    private BusinessStatisticsService businessStatisticsService;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 分页查询业务统计列表
     * GET /admin/business-stats
     */
    @GetMapping("/business-stats")
    public Result<PageResult<BusinessStatistics>> list(PageQuery query, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 构建分页对象
        Page<BusinessStatistics> page = new Page<>(query.getCurrentPage(), query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<BusinessStatistics> queryWrapper = new LambdaQueryWrapper<>();
        
        // 日期范围查询
        if (query.getStartDate() != null && !query.getStartDate().trim().isEmpty()) {
            LocalDate startDate = LocalDate.parse(query.getStartDate(), DATE_FORMATTER);
            queryWrapper.ge(BusinessStatistics::getStatDate, startDate);
        }
        if (query.getEndDate() != null && !query.getEndDate().trim().isEmpty()) {
            LocalDate endDate = LocalDate.parse(query.getEndDate(), DATE_FORMATTER);
            queryWrapper.le(BusinessStatistics::getStatDate, endDate);
        }
        
        // 管理员可以查看所有数据，普通用户只能查看自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(BusinessStatistics::getUserId, userId);
        }

        // 按日期倒序排列
        queryWrapper.orderByDesc(BusinessStatistics::getStatDate);

        // 执行分页查询
        Page<BusinessStatistics> resultPage = businessStatisticsService.page(page, queryWrapper);

        // 构造返回结果
        PageResult<BusinessStatistics> pageResult = new PageResult<>(
            resultPage.getRecords(),
            resultPage.getTotal(),
            query.getCurrentPage(),
            query.getPageSize()
        );

        return Result.success(pageResult);
    }

    /**
     * 新增业务统计
     * POST /admin/business-stats
     */
    @PostMapping("/business-stats")
    public Result<BusinessStatistics> add(@RequestBody BusinessStatistics businessStatistics, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 参数校验
        if (businessStatistics.getStatDate() == null) {
            return Result.error("统计日期不能为空");
        }

        // 检查该日期是否已存在统计数据（仅检查当前用户的数据）
        LambdaQueryWrapper<BusinessStatistics> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(BusinessStatistics::getStatDate, businessStatistics.getStatDate());
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            checkWrapper.eq(BusinessStatistics::getUserId, userId);
        }
        BusinessStatistics existData = businessStatisticsService.getOne(checkWrapper);
        
        if (existData != null) {
            return Result.error("该日期已存在统计数据");
        }

        // 数据校验
        if (businessStatistics.getQcPassRate() != null) {
            if (businessStatistics.getQcPassRate().doubleValue() < 0 || 
                businessStatistics.getQcPassRate().doubleValue() > 100) {
                return Result.error("质检通过率取值范围：0-100");
            }
        }
        
        // 设置用户ID
        businessStatistics.setUserId(userId);

        // 保存数据
        boolean success = businessStatisticsService.save(businessStatistics);
        if (success) {
            return Result.success(businessStatistics);
        } else {
            return Result.error("新增失败");
        }
    }

    /**
     * 修改业务统计
     * PUT /admin/business-stats/{id}
     */
    @PutMapping("/business-stats/{id}")
    public Result<BusinessStatistics> update(@PathVariable Long id, 
                                             @RequestBody BusinessStatistics businessStatistics, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 构建查询条件
        LambdaQueryWrapper<BusinessStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStatistics::getId, id);
        // 管理员可以修改所有数据，普通用户只能修改自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(BusinessStatistics::getUserId, userId);
        }
        
        // 检查数据是否存在
        BusinessStatistics existData = businessStatisticsService.getOne(queryWrapper);
        if (existData == null) {
            return Result.error("数据不存在或无权限修改");
        }

        // 设置ID
        businessStatistics.setId(id);

        // 如果修改了日期，检查新日期是否已存在（仅检查当前用户的数据）
        if (businessStatistics.getStatDate() != null && 
            !businessStatistics.getStatDate().equals(existData.getStatDate())) {
            LambdaQueryWrapper<BusinessStatistics> dateCheckWrapper = new LambdaQueryWrapper<>();
            dateCheckWrapper.eq(BusinessStatistics::getStatDate, businessStatistics.getStatDate());
            if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
                dateCheckWrapper.eq(BusinessStatistics::getUserId, userId);
            }
            BusinessStatistics dataByDate = businessStatisticsService.getOne(dateCheckWrapper);
            if (dataByDate != null && !dataByDate.getId().equals(id)) {
                return Result.error("该日期已存在统计数据");
            }
        }

        // 数据校验
        if (businessStatistics.getQcPassRate() != null) {
            if (businessStatistics.getQcPassRate().doubleValue() < 0 || 
                businessStatistics.getQcPassRate().doubleValue() > 100) {
                return Result.error("质检通过率取值范围：0-100");
            }
        }
        
        // 设置用户ID
        businessStatistics.setUserId(existData.getUserId());

        // 更新数据
        boolean success = businessStatisticsService.updateById(businessStatistics);
        if (success) {
            return Result.success(businessStatisticsService.getById(id));
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 删除业务统计
     * DELETE /admin/business-stats/{id}
     */
    @DeleteMapping("/business-stats/{id}")
    public Result<Void> delete(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 构建查询条件
        LambdaQueryWrapper<BusinessStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStatistics::getId, id);
        // 管理员可以删除所有数据，普通用户只能删除自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(BusinessStatistics::getUserId, userId);
        }
        
        // 检查数据是否存在
        BusinessStatistics existData = businessStatisticsService.getOne(queryWrapper);
        if (existData == null) {
            return Result.error("数据不存在或无权限删除");
        }

        // 删除数据
        boolean success = businessStatisticsService.removeById(id);
        if (success) {
            return Result.success(null);
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 根据ID查询业务统计详情
     * GET /admin/business-stats/{id}
     */
    @GetMapping("/business-stats/{id}")
    public Result<BusinessStatistics> getById(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 构建查询条件
        LambdaQueryWrapper<BusinessStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStatistics::getId, id);
        // 管理员可以查看所有数据，普通用户只能查看自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(BusinessStatistics::getUserId, userId);
        }
        
        BusinessStatistics data = businessStatisticsService.getOne(queryWrapper);
        if (data == null) {
            return Result.error("数据不存在或无权限查看");
        }
        return Result.success(data);
    }

    /**
     * 下载Excel模板
     * GET /admin/business-stats/template
     */
    @GetMapping("/business-stats/template")
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("业务统计导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 创建空模板（只有表头）
            List<BusinessStatisticsExcelDTO> templateData = new ArrayList<>();

            // 写入Excel（只生成表头，不含数据）
            EasyExcel.write(response.getOutputStream(), BusinessStatisticsExcelDTO.class)
                    .sheet("业务统计数据")
                    .doWrite(templateData);

            log.info("下载Excel模板成功");
        } catch (IOException e) {
            log.error("下载Excel模板失败", e);
            throw new RuntimeException("下载模板失败: " + e.getMessage());
        }
    }

    /**
     * 批量导入Excel数据
     * POST /admin/business-stats/import
     * 支持大文件导入，使用监听器模式逐行读取
     */
    @PostMapping("/business-stats/import")
    public Result<ImportResultDTO> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要导入的文件");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return Result.error("仅支持Excel文件格式（.xlsx或.xls）");
        }

        try {
            log.info("开始导入Excel文件: {}", fileName);

            // 创建导入结果对象
            ImportResultDTO importResult = new ImportResultDTO();

            // 使用监听器模式读取Excel，支持大文件
            BusinessStatisticsImportListener listener = new BusinessStatisticsImportListener(businessStatisticsService, importResult);
            listener.setUserId(userId); // 设置用户ID，用于导入时关联数据
            
            EasyExcel.read(file.getInputStream(), 
                          BusinessStatisticsExcelDTO.class, 
                          listener)
                    .sheet()
                    .doRead();

            log.info("导入完成: 总行数={}, 成功={}, 失败={}", 
                    importResult.getTotalRows(), 
                    importResult.getSuccessRows(), 
                    importResult.getFailRows());

            return Result.success(importResult);

        } catch (IOException e) {
            log.error("导入Excel文件失败", e);
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("导入Excel文件异常", e);
            return Result.error("导入异常: " + e.getMessage());
        }
    }
}